import { createContext, useRef, ReactNode, useContext } from 'react';

interface NewTaskCardShowFocusContextProps {
  registerCard: (name: string, ref: HTMLDivElement) => void;
  showCard: (name: string) => void;
  removeShowCard(): void;
}

const NewTaskCardShowFocusContext = createContext<NewTaskCardShowFocusContextProps | undefined>(undefined);

interface InputFocusProviderProps {
  children: ReactNode;
}

export const NewTaskCardProvider: React.FC<InputFocusProviderProps> = ({ children }) => {
  const taskCardRefs = useRef<{ [key: string]: HTMLDivElement }>({});

  const registerCard = (name: string, ref: HTMLDivElement) => {
    if (taskCardRefs.current !== null) taskCardRefs.current[name] = ref;
  };

  const removeShowCard = () => {
    for (const key in taskCardRefs.current) {
      if (taskCardRefs.current[key] !== null) {
        if (Object.prototype.hasOwnProperty.call(taskCardRefs.current, key)) {
          taskCardRefs.current[key].classList.remove('visible');
          taskCardRefs.current[key].classList.add('invisible');
        }
      }
    }
  }

  const showCard = (name: string) => {
    removeShowCard()
    if (taskCardRefs.current[name]) {
      taskCardRefs.current[name].classList.remove('invisible');
      taskCardRefs.current[name].classList.add('visible');
    }
  };

  return (
    <NewTaskCardShowFocusContext.Provider value={{ registerCard, showCard, removeShowCard }}>
      {children}
    </NewTaskCardShowFocusContext.Provider>
  );
};

export const useNewTaskCardContext = (): NewTaskCardShowFocusContextProps => {
  const context = useContext(NewTaskCardShowFocusContext);
  if (!context) {
    throw new Error('NewTaskCardShowFocusContext must be used within a NewTaskCardShowFocusProvider');
  }
  return context;
};

export default useNewTaskCardContext;



